#include "httpServer.hpp"
#include <memory>

using namespace std;
using namespace server;

void Usage(const string &proc)
{
    cout << "\nUsage:\n\t" << proc << " local_port\n"
         << endl;
}

bool Get(const HttpRequest &req, HttpResponse &resp)
{
    cout << "------------------http start---------------------" << endl;
    cout << req.inbuffer << endl;
    cout << "method: " << req.method << endl;
    cout << "url: " << req.url << endl;
    cout << "path: " << req.path << endl;
    cout << "httpversion: " << req.httpversion << endl;
    cout << "suffix: " << req.suffix << endl;
    cout << "size: " << req.size << "字节" << endl;
    cout << "-------------------http end---------------------" << endl;

    // string respLine = "HTTP/1.1 200 OK\r\n";
    string respLine = "HTTP/1.1 307 Temporary Redirect\r\n";        // 临时重定向

    // string respHeader = "Content-Type:text/html\r\n";
    string respHeader = Util::suffixToDesc(req.suffix);

    if (req.size > 0)
    {
        respHeader += "Content-Length:";
        respHeader += to_string(req.size);
        respHeader += "\r\n";
    }

    // respHeader += "Location:https://gitee.com/Code-king-chb\r\n";      // 临时重定向的网址
    respHeader += "Set-Cookie:name=20240406abc;Max-Age=100\r\n";          // 设置cookie，100s到期
    // 第一次请求时，服务器会返回cookie，往后每次请求就都会携带cookie，帮服务器进行鉴权行为
    // 如果cookie过期，那么就不会再携带了
    
    string respBlank = "\r\n";
    // string body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>chb for test</title><h1>Hello world!</h1><h2>Hello world!</h2><h3>Hello world!</h3></head><body><p>在不久前的美加墨世界杯亚洲区预选赛36强赛中，换帅后的中国队面对亚洲弱旅新加坡队，在主场作战的情况，依靠武磊的精彩表现，击败对手，全取三分，保留了中国队小组出线的希望，这场胜利也是国足亚洲杯以来的首场胜利。这边国足终于赢球了，另一边的国奥队也终于传来了久违的赢球消息。据相关媒体的报道，在一场封闭的比赛中，中国国奥队以2：0战胜了卡塔尔U23队，在连败之后终于收获了一场难得的胜利。不过，就算国奥队赢球了，但有不少球迷表示，还是希望这支国奥队能够更换主教练。</p></body></html>";

    string body;
    body.clear();
    if (!Util::readFile(req.path, &body))
    {
        Util::readFile(html_404, &body); // 一定存在这个文件，不会出错
    }

    resp.outbuffer += respLine;
    resp.outbuffer += respHeader;
    resp.outbuffer += respBlank;

    cout << "------------------response start--------------" << endl;
    cout << "body size: " << body.size() << endl;
    cout << "response: " << resp.outbuffer << endl; 
    cout << "------------------response end----------------" << endl;

    resp.outbuffer += body;

    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]);

    unique_ptr<HttpServer> tsvr(new HttpServer(port, Get));

    tsvr->initServer();
    tsvr->run();

    // test();

    return 0;
}